﻿#include "DataPack.h"

void DataPack::Alloc(unsigned int size)
{
	this->size = size;
	if (buffer)
	{
		CC_SAFE_DELETE_ARRAY(buffer);
	}
	buffer = new char[this->size];
}

void DataPack::DeAlloc()
{
	if (buffer)
	{
		CC_SAFE_DELETE_ARRAY(buffer);
		this->size = 0;
	}
}

DataPack::~DataPack()
{
	this->DeAlloc();
}

DataPack*  DataPack::CreateWithCmd(Cmd*cmd, bool encode)
{
	return nullptr;
}

DataPack* DataPack::CreateWithMask(int mask)
{
	DataPack * ret = new DataPack;
	if (mask < 0)
	{
		ret->_isEncode = true;
	}
	else
	{
		ret->_isEncode = false;
	}
	ret->size = abs(mask);
	return ret;
}

DataPack* DataPack::CreateWithString(const std::string &s, bool encode)
{
	DataPack *ret = CreateWithRawData(s.c_str(), s.size(), encode);
	return ret;
}
DataPack*DataPack::CreateWithRawData(const char * data, int size, bool encode)
{
	DataPack * ret = new DataPack;

	unsigned int len = size;
	std::vector <char> buf;
	for (int ii = 0; ii < sizeof(unsigned int); ii++)
	{
		char  *addr = (char*)(&len);
		buf.push_back(*(addr + ii));
	}
	for (int ii = 0; ii < len; ii++)
	{
		buf.push_back(data[ii]);
	}
	ret->size = buf.size();
	ret->Alloc(ret->size);
	memset(ret->buffer, '\0', buf.size());
	memcpy(ret->buffer, &buf[0], buf.size());
	ret->_isEncode = encode;
	return ret;
}

void DataPack::Encode()
{
	int ret = compress(0, 0, 0, 0);
}

void DataPack::Decode()
{
	int ret = uncompress(0, 0, 0, 0);
}